// Markdown编辑器类
class MarkdownEditor {
    constructor(element) {
        this.element = element;
        this.codemirror = null;
        this.changeCallback = null;
        
        this.init();
    }

    init() {
        if (typeof CodeMirror !== 'undefined') {
            this.initCodeMirror();
        } else {
            console.warn('CodeMirror未加载，使用简单编辑器');
            this.initSimpleEditor();
        }
    }

    // 初始化CodeMirror
    initCodeMirror() {
        this.codemirror = CodeMirror.fromTextArea(this.element, {
            mode: 'markdown',
            theme: 'default',
            lineNumbers: true,
            lineWrapping: true,
            autoCloseBrackets: true,
            matchBrackets: true,
            foldGutter: true,
            gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
            extraKeys: {
                'Ctrl-Space': 'autocomplete',
                'Ctrl-/': 'toggleComment',
                'Ctrl-B': () => this.insertText('**', '**'),
                'Ctrl-I': () => this.insertText('*', '*'),
                'Ctrl-K': () => this.insertText('[', '](url)'),
                'Tab': (cm) => {
                    if (cm.somethingSelected()) {
                        cm.indentSelection('add');
                    } else {
                        cm.replaceSelection('    ');
                    }
                }
            },
            placeholder: '在这里输入Markdown内容...'
        });

        // 监听内容变化
        this.codemirror.on('change', (cm) => {
            if (this.changeCallback) {
                this.changeCallback(cm.getValue());
            }
            this.updateCursorPosition();
            
            // 触发内容变化事件，供目录管理器使用
            document.dispatchEvent(new CustomEvent('editorContentChanged', {
                detail: { content: cm.getValue() }
            }));
        });

        // 监听光标位置变化
        this.codemirror.on('cursorActivity', () => {
            this.updateCursorPosition();
        });

        // 设置初始焦点
        setTimeout(() => {
            this.codemirror.focus();
        }, 100);
    }

    // 初始化简单编辑器
    initSimpleEditor() {
        this.element.style.display = 'block';
        this.element.addEventListener('input', () => {
            if (this.changeCallback) {
                this.changeCallback(this.element.value);
            }
            this.updateCursorPosition();
            
            // 触发内容变化事件，供目录管理器使用
            document.dispatchEvent(new CustomEvent('editorContentChanged', {
                detail: { content: this.element.value }
            }));
        });

        this.element.addEventListener('keydown', (e) => {
            this.handleKeydown(e);
        });
    }

    // 处理键盘事件
    handleKeydown(e) {
        if (e.ctrlKey || e.metaKey) {
            switch (e.key) {
                case 'b':
                    e.preventDefault();
                    this.insertText('**', '**');
                    break;
                case 'i':
                    e.preventDefault();
                    this.insertText('*', '*');
                    break;
                case 'k':
                    e.preventDefault();
                    this.insertText('[', '](url)');
                    break;
            }
        }

        // Tab键处理
        if (e.key === 'Tab') {
            e.preventDefault();
            this.insertText('    ', '');
        }

        // Enter键自动缩进
        if (e.key === 'Enter') {
            setTimeout(() => {
                this.autoIndent();
            }, 0);
        }
    }

    // 自动缩进
    autoIndent() {
        if (this.codemirror) return; // CodeMirror自己处理

        const textarea = this.element;
        const lines = textarea.value.split('\n');
        const currentLineIndex = textarea.value.substr(0, textarea.selectionStart).split('\n').length - 1;
        const currentLine = lines[currentLineIndex];
        const previousLine = lines[currentLineIndex - 1];

        if (previousLine) {
            // 检查是否是列表项
            const listMatch = previousLine.match(/^(\s*)([-*+]|\d+\.)\s/);
            if (listMatch) {
                const indent = listMatch[1];
                const marker = listMatch[2];
                let newMarker = marker;
                
                if (/\d+\./.test(marker)) {
                    const num = parseInt(marker) + 1;
                    newMarker = num + '.';
                }
                
                const insertion = indent + newMarker + ' ';
                this.insertTextAtCursor(insertion);
            }
            // 检查是否是引用
            else if (previousLine.match(/^(\s*>)/)) {
                const match = previousLine.match(/^(\s*>+\s*)/);
                if (match) {
                    this.insertTextAtCursor(match[1]);
                }
            }
        }
    }

    // 在光标位置插入文本
    insertTextAtCursor(text) {
        if (this.codemirror) {
            this.codemirror.replaceSelection(text);
        } else {
            const textarea = this.element;
            const start = textarea.selectionStart;
            const end = textarea.selectionEnd;
            const value = textarea.value;
            
            textarea.value = value.substring(0, start) + text + value.substring(end);
            textarea.selectionStart = textarea.selectionEnd = start + text.length;
            textarea.focus();
        }
    }

    // 插入包围文本
    insertText(before, after) {
        if (this.codemirror) {
            const selection = this.codemirror.getSelection();
            if (selection) {
                this.codemirror.replaceSelection(before + selection + after);
            } else {
                this.codemirror.replaceSelection(before + after);
                const cursor = this.codemirror.getCursor();
                this.codemirror.setCursor(cursor.line, cursor.ch - after.length);
            }
            this.codemirror.focus();
        } else {
            const textarea = this.element;
            const start = textarea.selectionStart;
            const end = textarea.selectionEnd;
            const selectedText = textarea.value.substring(start, end);
            const replacement = before + selectedText + after;
            
            textarea.value = textarea.value.substring(0, start) + replacement + textarea.value.substring(end);
            
            if (selectedText) {
                textarea.selectionStart = start;
                textarea.selectionEnd = start + replacement.length;
            } else {
                textarea.selectionStart = textarea.selectionEnd = start + before.length;
            }
            textarea.focus();
        }
    }

    // 获取内容
    getValue() {
        return this.codemirror ? this.codemirror.getValue() : this.element.value;
    }

    // 设置内容
    setValue(value) {
        if (this.codemirror) {
            this.codemirror.setValue(value);
        } else {
            this.element.value = value;
        }
    }

    // 设置变化回调
    onChange(callback) {
        this.changeCallback = callback;
    }

    // 更新光标位置显示
    updateCursorPosition() {
        let line = 1, col = 1;
        
        if (this.codemirror) {
            const cursor = this.codemirror.getCursor();
            line = cursor.line + 1;
            col = cursor.ch + 1;
        } else {
            const textarea = this.element;
            const text = textarea.value.substring(0, textarea.selectionStart);
            const lines = text.split('\n');
            line = lines.length;
            col = lines[lines.length - 1].length + 1;
        }
        
        const positionElement = document.getElementById('cursor-position');
        if (positionElement) {
            positionElement.textContent = `行 ${line}, 列 ${col}`;
        }
    }

    // 聚焦编辑器
    focus() {
        if (this.codemirror) {
            this.codemirror.focus();
        } else {
            this.element.focus();
        }
    }

    // 获取选中文本
    getSelection() {
        if (this.codemirror) {
            return this.codemirror.getSelection();
        } else {
            const textarea = this.element;
            return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
        }
    }

    // 替换选中文本
    replaceSelection(text) {
        if (this.codemirror) {
            this.codemirror.replaceSelection(text);
        } else {
            const textarea = this.element;
            const start = textarea.selectionStart;
            const end = textarea.selectionEnd;
            textarea.value = textarea.value.substring(0, start) + text + textarea.value.substring(end);
            textarea.selectionStart = textarea.selectionEnd = start + text.length;
        }
    }

    // 刷新编辑器
    refresh() {
        if (this.codemirror) {
            setTimeout(() => {
                this.codemirror.refresh();
            }, 0);
        }
    }

    // 插入行内数学公式
    insertInlineMath() {
        this.insertText('$', '$');
    }

    // 插入块级数学公式
    insertBlockMath() {
        const newline = this.codemirror ? '\n' : '\n';
        this.insertText(`${newline}$$${newline}`, `${newline}$$${newline}`);
    }

    // 插入常用数学符号
    insertMathSymbol(symbol) {
        this.insertTextAtCursor(symbol);
    }

    // 插入数学模板
    insertMathTemplate(template) {
        this.insertTextAtCursor(template);
    }

    // 插入表格
    insertTable(rows = 3, cols = 3) {
        let table = '\n';
        // 表头
        table += '|';
        for (let i = 0; i < cols; i++) {
            table += ` 列${i + 1} |`;
        }
        table += '\n';
        
        // 分隔线
        table += '|';
        for (let i = 0; i < cols; i++) {
            table += ' --- |';
        }
        table += '\n';
        
        // 数据行
        for (let i = 0; i < rows - 1; i++) {
            table += '|';
            for (let j = 0; j < cols; j++) {
                table += '  |';
            }
            table += '\n';
        }
        
        this.insertTextAtCursor(table);
    }

    // 插入代码块
    insertCodeBlock(language = '') {
        const code = `\n\`\`\`${language}\n\n\`\`\`\n`;
        this.insertTextAtCursor(code);
        
        // 将光标定位到代码块内部
        if (this.codemirror) {
            const cursor = this.codemirror.getCursor();
            this.codemirror.setCursor(cursor.line - 2, 0);
        }
    }
}

// 简单编辑器类（降级方案）
class SimpleEditor {
    constructor(element) {
        this.element = element;
        this.changeCallback = null;
        
        this.init();
    }

    init() {
        this.element.addEventListener('input', () => {
            if (this.changeCallback) {
                this.changeCallback(this.element.value);
            }
        });
    }

    getValue() {
        return this.element.value;
    }

    setValue(value) {
        this.element.value = value;
    }

    onChange(callback) {
        this.changeCallback = callback;
    }

    insertText(before, after) {
        const start = this.element.selectionStart;
        const end = this.element.selectionEnd;
        const selectedText = this.element.value.substring(start, end);
        const replacement = before + selectedText + after;
        
        this.element.value = this.element.value.substring(0, start) + replacement + this.element.value.substring(end);
        
        if (selectedText) {
            this.element.selectionStart = start;
            this.element.selectionEnd = start + replacement.length;
        } else {
            this.element.selectionStart = this.element.selectionEnd = start + before.length;
        }
        this.element.focus();
    }

    focus() {
        this.element.focus();
    }
}